package com.aaa.zs.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component //交给SpringMVC容器
public class IllegalPFilter extends ZuulFilter {
    //spring 读取 读取自定义配置文件中的配置值赋值给属性
    @Value("${illegal_ip}")
    private String illegalIp;
    @Override
    public String filterType() {
        //过滤器的使用类型
        //pre  在调用后台微服务中业务方法之前  调用该过滤器
        //route  调用时   调用过滤器
        //post   调用后   调用过滤器
        //error  异常时   调用过滤器
        return "pre";
    }

    @Override
    public int filterOrder() {
        //多个filter时，当前filter执行的优先级  返回值越小，优先级越高，越先执行
        return 5;
    }

    @Override
    public boolean shouldFilter() {
        //是否让当前过滤器生效  true生效 false失效
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //具体过滤器业务代码
        System.out.println("进入了IP过滤器。。。");
        //获取zuul中提供的上下文对象
        RequestContext requestContext=RequestContext.getCurrentContext();
        //获取request  response
        HttpServletRequest request=requestContext.getRequest();
        HttpServletResponse response=requestContext.getResponse();
        //获取请求用户的IP地址
        String remoteAddr=request.getRemoteAddr();
        System.out.println("请求IP为:"+remoteAddr);
        //判断IP地址是否合法
//        if ("192.168.1.120".equals(remoteAddr)||"192.168.1.110".equals(remoteAddr)){}
        if (illegalIp.contains(remoteAddr)){
            //阻止程序继续运行
            requestContext.setSendZuulResponse(false);
            //添加响应方法
            try {
                response.setCharacterEncoding("utf-8");
                response.sendError(HttpStatus.SC_FORBIDDEN,"你的IP非法，不能访问网站！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null ;
    }
}
